package com.lee.common.base

import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.qmuiteam.qmui.arch.QMUIFragment
import org.greenrobot.eventbus.EventBus

abstract class NewLazyFragment : QMUIFragment() {

    private var isFirstLoad = true // 是否第一次加载
    private var isHiddenChanged = false

    open fun registerEvent(objects: Any) {
        EventBus.getDefault().apply {
            if (!isRegistered(objects)) {
                register(objects)
            }
        }
    }

    fun destroyEvent(activity: Any) {
        EventBus.getDefault().unregister(activity)
    }

    protected open fun isVisible(isVisible: Boolean) {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initView(view)
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            initData()
            initEvent()
            isFirstLoad = false
        } else {
            if (!isHiddenChanged)
                isVisible(true)
        }
    }

    override fun onPause() {
        if (!isHiddenChanged)
            isVisible(false)
        super.onPause()
    }


    override fun onHiddenChanged(hidden: Boolean) {
        isHiddenChanged = hidden
        isVisible(!hidden)
        super.onHiddenChanged(hidden)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        isVisible(isVisibleToUser)
        if (isVisibleToUser) {
            //界面可见
        } else {
            //界面不可见 相当于onpause
        }
    }

    abstract fun initData()


    /**
     * 初始化视图
     */
    protected open fun initView(view: View) {

    }


    /**
     * 初始化事件
     */
    protected open fun initEvent() {

    }

}